const groupIcon = require('@/assets/icons/style/group.png')
const highlightIcon = require('@/assets/icons/style/highlight.png')

import { clear as subfieldClear } from './subfield.js'
const controls = document.createElement('div')
controls.id = 'group-chunk-controls'
controls.innerHTML = `
    <div class="group-chunk">
        <img class="group-icon" src="${ groupIcon }" title="样式组"/>
        <div class="controls-float" style="visibility:hidden">
            <div class="isEmpty">
                <p class="copy"><img src="${require('@/assets/icons/style/copy.png')}" />复制</p>
                <p class="cut"><img src="${require('@/assets/icons/style/cut.png')}" />剪切</p>
                <p class="del"><img src="${require('@/assets/icons/style/del.png')}" />删除</p>
                <div class="line-nodel"></div>
                <p title="前插空行" class="topset"><img src="${require('@/assets/icons/style/topset.png')}" />在上方插入空行</p>
                <p title="后插空行" class="bottomset"><img src="${require('@/assets/icons/style/bottomset.png')}" />在下方插入空行</p>
            </div>
        </div>
    </div>
  `
// 组块菜单 & 子节点
const groupControls = controls.querySelector('.group-chunk')
const controlsDom = groupControls.querySelectorAll('.controls-float')[0]
const groupIconDom = groupControls.querySelectorAll('.group-icon')[0]
let activeEditor = null
let oldTop = 0;
let oldscrollTop = 0;
let chunkDom = null;
let iframeDom = null
let tinymceDom = null
let isShowControls = false


function groupInit(editor) {
    activeEditor = editor
    document.querySelectorAll('.tox-sidebar-wrap')[0].appendChild(controls)
    tinymceDom = editor.dom.select('#tinymce')[0]
    iframeDom = document.querySelectorAll(`#${editor.id}_ifr`)[0]
    tinymceDom.addEventListener('mousemove', mouseMove)
    iframeDom.addEventListener('mouseout', moveOut)
    iframeDom.contentWindow.document.addEventListener('scroll', scrollHandle)
    editor.on('click', (e)=>{
        closeStyleHandle()
        // 关闭自定义卡片
        const cardCustomBtnActive = editor.dom.select('.card-autonomy-editor-menu-active')[0]
        const cardAutonomySelect = findParentWithClass(cardCustomBtnActive, 'card-autonomy-editor')
        const cardAutonomyActive = findParentWithClass(e.target, 'card-autonomy-editor')
        console.log('关闭自定义卡片', cardAutonomySelect, cardAutonomyActive)
        if (cardAutonomyActive && cardAutonomySelect){
            let editorUuid = cardAutonomyActive.getAttribute('data-uuid')
            let activeUuid = cardAutonomyActive.getAttribute('data-uuid')
            if (editorUuid == activeUuid){
                return;
            }
        }
        const cardCustomBtn = cardAutonomySelect && cardAutonomySelect.querySelector('.card-autonomy-editor-btn')
        if(cardCustomBtn)cardCustomBtn.style.visibility = 'hidden'
        if (cardCustomBtnActive)cardCustomBtnActive.classList.remove('card-autonomy-editor-menu-active')
    })
};

// 鼠标移动事件
function mouseMove(e) {
    const target = e.target
    // 自定义卡片操作区显示(其他功能)
    let cardCustom = findParentWithClass(target, 'card-autonomy-editor')
    if (cardCustom){
        let cardCustomBtn = cardCustom.querySelector('.card-autonomy-editor-btn')
        if (cardCustomBtn) {
            cardCustomBtn.style.visibility = 'visible'
        }
    }
    // end
    let effectiveDom = findParentWithClass(target, 'group-box')
    let hasClassName = ['divide-box', 'css-box-item', 'insert-element']
    if (!findParentWithClass(target, hasClassName) && !isShowControls) {
        console.log('没有找到样式组')
        closeStyleHandle()
    }

    if (effectiveDom && !isShowControls) {
        // 获取iframe的滚动条高度
        let scrollTop = iframeDom.contentWindow.document.documentElement.scrollTop
        // 距离父级顶部高度
        let offsetTop = effectiveDom.offsetTop
        let top = offsetTop - scrollTop
        oldTop = top
        oldscrollTop = scrollTop
        controls.style.top = top + 'px'
        groupControls.style.visibility = 'visible'
        chunkDom = effectiveDom
    }
    if (effectiveDom){
        if (isShowControls) return
        if (effectiveDom.classList?.contains('exclude-subfield')) {
            groupIconDom.src = highlightIcon
        }else{
            groupIconDom.src = groupIcon
        }
    }
}

// 移出样式组后隐藏icon图标
function moveOut(e){
    e.stopPropagation()
    scrollHandle()
}
controls.addEventListener('mouseenter', () => {
    groupControls.style.visibility = 'visible'
    activeEditor.dom.addClass(chunkDom, 'highlight-boder-line')
    
})
controls.addEventListener('mouseleave', () => {
    activeEditor.dom.removeClass(chunkDom, 'highlight-boder-line')
})
// b编辑器滚动事件
function scrollHandle(e) {
    let scrollTop = iframeDom.contentWindow.document.documentElement.scrollTop
    if (isShowControls) {
        controls.style.top = (oldTop + oldscrollTop - scrollTop) + 'px'
    }
}
// 菜单图标点击事件
groupIconDom.addEventListener('click', (e) => {
    subfieldClear()
    if (controlsDom.style.visibility == 'hidden') {
        controlsDom.style.visibility = 'visible'
        controlsDom.style.transform = 'scale(1)'
        controlsDom.style.opacity = '1'
        isShowControls = true
        let iconRect = e.target.getBoundingClientRect()
        let differenceTop = (window.innerHeight - iconRect.top) - controlsDom.clientHeight
        if (differenceTop < 0) {
            controlsDom.style.top = differenceTop - 20 + 'px'
            controlsDom.style.right = '120%'
        } else {
            controlsDom.style.top = ''
            controlsDom.style.right = ''
        }
    } else {
        controlsDom.style.visibility = 'hidden'
        controlsDom.style.transform = 'scale(.8)'
        controlsDom.style.opacity = '0'
        isShowControls = false
    }
})

// 关闭样式组操作菜单
function closeStyleHandle(){
    groupControls.style.visibility = 'hidden'
    controlsDom.style.visibility = 'hidden'
    // controls.style.top = 0 + 'px'
    controlsDom.style.transform = 'scale(.8)'
    controlsDom.style.opacity = '0'
    isShowControls = false
}

// 菜单列表点击事件
controlsDom.addEventListener('click', async (e) => {
    e.stopPropagation()
    const childItem = ['copy', 'cut', 'del', 'topset', 'bottomset']
    if (childItem.includes((e.target.className || e.target.parentNode.className))) {
        // 事件类型
        const funType = e.target.className || e.target.parentNode.className
        console.log(funType, '点击事件')
        if (funType == 'copy') {
            // 复制高亮块
            if (chunkDom) {
                const rng = activeEditor.dom.createRng();
                rng.setStartBefore(chunkDom); // 设置选区的起始位置在目标元素之前
                rng.setEndAfter(chunkDom);   // 设置选区的结束位置在目标元素之后
                // 使用编辑器的selection对象设置新的选区
                activeEditor.selection.setRng(rng);
                const contentToCopy = activeEditor.selection.getContent({ format: 'html' })// 获取块级元素的HTML内容
                const blob = new Blob([contentToCopy], { type: 'text/html' });
                const item = new ClipboardItem({ 'text/html': blob });
                await navigator.clipboard.write([item]);
                console.log('复制内容成功')
            }

        } else if (funType == 'cut') {
            // 剪切高亮块
            if (chunkDom) {
                const rng = activeEditor.dom.createRng();
                rng.setStartBefore(chunkDom); // 设置选区的起始位置在目标元素之前
                rng.setEndAfter(chunkDom);   // 设置选区的结束位置在目标元素之后
                // 使用编辑器的selection对象设置新的选区
                activeEditor.selection.setRng(rng);
                const contentToCopy = activeEditor.selection.getContent({ format: 'html' })// 获取块级元素的HTML内容
                const blob = new Blob([contentToCopy], { type: 'text/html' });
                const item = new ClipboardItem({ 'text/html': blob });
                await navigator.clipboard.write([item]);
                activeEditor.dom.remove(chunkDom)
            }

        } else if (funType == 'del') {
            // 删除高亮块
            if (chunkDom) {
                activeEditor.dom.remove(chunkDom)
            }

        } else if (funType == 'topset') {
            // 顶部插入一行
            if (chunkDom) {
                const newRow = activeEditor.dom.create('div', {}, '<br>');
                chunkDom.parentNode.insertBefore(newRow, chunkDom)
            }
        } else if (funType == 'bottomset') {
            // 底部插入一行
            if (chunkDom) {
                const newRow = activeEditor.dom.create('div', {}, '<br>');
                activeEditor.dom.insertAfter(newRow, chunkDom)
            }
        }
        // 隐藏面板
        closeStyleHandle()
    }
 })
// 找到指定dom
function findParentWithClass(element, className) {
    if (!element || element === tinymceDom) {
        return false;
    }
    if (className instanceof Array){
        let flag = className.some(item => element.classList.contains(item))
        if(flag){
            return element
        }
    }else{
        if (element.classList?.contains(className)) {
            return element;
        }
    }
    return findParentWithClass(element.parentNode, className);
}


export {
    groupInit,
    closeStyleHandle,
    findParentWithClass
}